package attendance

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/attendance"
	attendanceReq "github.com/flipped-aurora/gin-vue-admin/server/model/attendance/request"
)

type SignRecordService struct {
}

// CreateSignRecord 创建考勤记录记录
// Author [piexlmax](https://github.com/piexlmax)
func (signreService *SignRecordService) CreateSignRecord(signre *attendance.SignRecord) (err error) {
	err = global.GVA_DB.Create(signre).Error
	return err
}

// DeleteSignRecord 删除考勤记录记录
// Author [piexlmax](https://github.com/piexlmax)
func (signreService *SignRecordService) DeleteSignRecord(ID string) (err error) {
	err = global.GVA_DB.Delete(&attendance.SignRecord{}, "id = ?", ID).Error
	return err
}

// DeleteSignRecordByIds 批量删除考勤记录记录
// Author [piexlmax](https://github.com/piexlmax)
func (signreService *SignRecordService) DeleteSignRecordByIds(IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]attendance.SignRecord{}, "id in ?", IDs).Error
	return err
}

// UpdateSignRecord 更新考勤记录记录
// Author [piexlmax](https://github.com/piexlmax)
func (signreService *SignRecordService) UpdateSignRecord(signre attendance.SignRecord) (err error) {
	err = global.GVA_DB.Model(&attendance.SignRecord{}).Where("id = ?", signre.ID).Updates(&signre).Error
	return err
}

// GetSignRecord 根据ID获取考勤记录记录
// Author [piexlmax](https://github.com/piexlmax)
func (signreService *SignRecordService) GetSignRecord(ID string) (signre attendance.SignRecord, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&signre).Error
	return
}

// GetSignRecordInfoList 分页获取考勤记录记录
// Author [piexlmax](https://github.com/piexlmax)
func (signreService *SignRecordService) GetSignRecordInfoList(info attendanceReq.SignRecordSearch, belongTo uint) (list []attendance.SignRecord, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&attendance.SignRecord{})
	db = db.Where("belong_to = ?", belongTo)
	var signres []attendance.SignRecord
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Stu_id != "" {
		db = db.Where("stu_id = ?", info.Stu_id)
	}
	if info.Sign_status != nil {
		db = db.Where("sign_status = ?", info.Sign_status)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&signres).Error
	return signres, total, err
}
